<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 当燃      
 * Date: 2015-09-21
 */

namespace Admin\Controller;

class EquipmentController extends BaseController{
    public function add(){       
        $act = I('GET.act','add');
        $ad_id = I('GET.ad_id');
        $ad_info = array();
        if($ad_id){
            $ad_info = D('ad')->where('ad_id='.$ad_id)->find();
            $ad_info['start_time'] = date('Y-m-d',$ad_info['start_time']);
            $ad_info['end_time'] = date('Y-m-d',$ad_info['end_time']);            
        }
        if($act == 'add')          
           $ad_info['pid'] = $_GET['pid'];                
        $position = D('ad_position')->where('1=1')->select();
        $this->assign('info',$ad_info);
        $this->assign('act',$act);
        $this->assign('position',$position);
        $this->display();
    }
    
    public function equipmentList(){
        
        delFile(RUNTIME_PATH.'Html'); // 先清除缓存, 否则不好预览
            
        $Ad =  M('equipment'); 
        $where = "1=1";
        if(I('equipment_type')){
        	$where = "equipment_type=".I('equipment_type');
            // dump($where);die();
        	$this->assign('equipment_type',I('equipment_type'));
        }
        $keywords = I('keywords',false);
        if($keywords){
        	$where = "equipment_name like '%$keywords%'";
        }
        $count = $Ad->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
        $res = $Ad->where($where)->order('equipment_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $list = array();
        if($res){
        	$media = array('图片','文字','flash');
        	foreach ($res as $val){
        		$val['media_type'] = $media[$val['media_type']]; 
                $val['equipment_img'] = "https://project.csnet.net.cn".substr($val['equipment_img'], 7);       		
        		$list[] = $val;

        	}
        }
                                     
        // $ad_position_list = M('AdPosition')->getField("position_id,position_name,is_open");                        
        // $this->assign('ad_position_list',$ad_position_list);//广告位 
        $show = $Page->show();// 分页显示输出
        $this->assign('list',$list);// 赋值数据集
        
        
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    // public function position(){
    //     $act = I('GET.act','add');
    //     $position_id = I('GET.position_id');
    //     $info = array();
    //     if($position_id){
    //         $info = D('ad_position')->where('position_id='.$position_id)->find();
    //         $this->assign('info',$info);
    //     }
    //     $this->assign('act',$act);
    //     $this->display();
    // }
    
    // public function positionList(){
    //     $Position =  M('ad_position');
    //     $count = $Position->where('1=1')->count();// 查询满足要求的总记录数
    //     $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
    //     $list = $Position->order('position_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        
    //     $this->assign('list',$list);// 赋值数据集                
    //     $show = $Page->show();// 分页显示输出
    //     $this->assign('page',$show);// 赋值分页输出
    //     $this->display();
    // }
    
    public function equipmentHandle(){
    	$data = I();

    // 	$data['start_time'] = strtotime($data['begin']);
    // 	$data['end_time'] = strtotime($data['end']);
    	
    	if($data['act'] == 'add'){
    		
            if($_FILES['equipment_img']['error'] == 0){

                // 配置文件
                $cfg = array('rootPath' => './../api/upload/equipment/', 'autoSub' => false, );

                $upload = new \Think\Upload($cfg);
                
                // 搜索数据库 equipment_shortCode / equipment_assdtNumber / equipment_sequenceNumber 有没有重复
                $shortCode = $data['equipment_shortCode'];
                $assdtNumber = $data['equipment_assdtNumber'];
                $sequenceNumber = $data['equipment_sequenceNumber'];
                $equipment = M('equipment')->where("equipment_shortCode =".$shortCode." OR "."equipment_assdtNumber=".$assdtNumber." OR "."equipment_sequenceNumber = ".$sequenceNumber)->find();

                if(empty($equipment)){
                    // 图片上传
                    $result = $upload -> uploadOne($_FILES['equipment_img']);
                    $pathname = $upload->rootPath.$result['savepath'].$result['savename'];
                    $data['equipment_img'] = substr($pathname, 1);
                    // 写入数据库
                    $r = D('equipment')->add($data); 
                    if($r){
                         $this->success("操作成功",$referurl);
                        }else{
                         $this->error("操作失败",$referurl);
                        }

                }else{
                    $this->error("设备短码、设备资产号、设备序列号重复!",$referurl);
                }
                
            }else {
                $this->error("请上传图片",$referurl);
            }
    	}
    	if($data['act'] == 'edit'){
          $arr =   $equipment = M('equipment')->where("equipment_id ={$data['equipment_id']}") ->find();
             $arr['equipment_img'] = "https://project.csnet.net.cn".substr( $arr['equipment_img'], 7);
            
           
                
                 $this -> assign('info', $arr);
                $this->display('Equipment/edit');
            }

    	}
    	
    // 	if($data['act'] == 'del'){
    // 		$r = D('ad')->where('ad_id='.$data['del_id'])->delete();
    // 		if($r) exit(json_encode(1));
    // 	}
    // 	$referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U('Admin/Ad/adList');
    //     // 不管是添加还是修改广告 都清除一下缓存
    //     delFile(RUNTIME_PATH.'Html'); // 先清除缓存, 否则不好预览
         
    	
    
    
    // public function positionHandle(){
    //     $data = I('post.');
    //     if($data['act'] == 'add'){
    //         $r = M('ad_position')->add($data);
    //     }
        
    //     if($data['act'] == 'edit'){
    //     	$r = M('ad_position')->where('position_id='.$data['position_id'])->save($data);
    //     }
        
    //     if($data['act'] == 'del'){
    //     	if(M('ad')->where('pid='.$data['position_id'])->count()>0){
    //     		$this->error("此广告位下还有广告，请先清除",U('Admin/Ad/positionList'));
    //     	}else{
    //     		$r = M('ad_position')->where('position_id='.$data['position_id'])->delete();
    //     		if($r) exit(json_encode(1));
    //     	}
    //     }
    //     $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U('Admin/Ad/positionList');
    //     if($r){
    //     	$this->success("操作成功",$referurl);
    //     }else{
    //     	$this->error("操作失败",$referurl);
    //     }
    // }
    
    // public function changeAdField(){
    // 	$data[$_REQUEST['field']] = I('GET.value');
    // 	$data['ad_id'] = I('GET.ad_id');
    // 	M('ad')->save($data); // 根据条件保存修改的数据
    // }

//删除
public function equipment_delete($id)
    {
        $equipment = D('equipment');
        $id =   $equipment -> where("equipment_id = {$id}") -> delete();
        
        if($id){
             $this->success("操作成功",U('Admin/Equipment/equipmentList'));
        }

   
    }




//修改
 public function equipment_save($id){
    $data = $_POST;
     if($_POST){
            $cfg = array('rootPath' => './../api/upload/equipment/', 'autoSub' => false, );

            $upload = new \Think\Upload($cfg);
                // 图片上传
            $result = $upload -> upload($_FILES);
            $bigpathname = $upload -> rootPath;

                    // 搜索数据库 equipment_shortCode / equipment_assdtNumber / equipment_sequenceNumber 有没有重复
                
                    $shortCode = $data['equipment_shortCode'];
                    $assdtNumber = $data['equipment_assdtNumber'];
                    $sequenceNumber = $data['equipment_sequenceNumber'];
                    $equipment = M('equipment')->where("equipment_shortCode =".$shortCode." OR "."equipment_assdtNumber=".$assdtNumber." OR "."equipment_sequenceNumber = ".$sequenceNumber)->find();

                    if(empty($equipment)){
                     if (!$result) {// 上传错误提示错误信息

                    $design_cases = M('equipment')->where("equipment_id = {$id}") ->find();
                    $dizi =$design_cases['equipment_img'];
                    
                    $data['equipment_img'] = "https://project.csnet.net.cn".substr($dizi, 7); 
                } else {// 上传成功 获取上传文件信息
                    foreach ($result as $file) {
                        //图片地址
                        $dizi = $bigpathname . $file['savepath'] . $file['savename'];
                        $data['equipment_img'] = "https://project.csnet.net.cn".substr($dizi, 7);
                    }
                }

                    
                   
                    $r = D('equipment')->where("equipment_id = {$id}")->save($data);
                    }else{
                        $this->error("设备短码、设备资产号、设备序列号重复!",$referurl);
                    }
                    
               

                if($r){
                    $this->success("操作成功",U('Admin/Equipment/equipmentList'));
                }else{
                    $this->error("操作失败",$referurl);
                }

         

 
}
}


    /*
     *获取商品二维码
    */
    public function get_qrcode($id){
        header('Content-Type:image/jpg');
        //先向数据库提取access_token的时间判断是否超过7200s
        date_default_timezone_set('PRC');
        $times =  time();       
        $access_token = D("access_token");
        $tokenlist = $access_token -> find();
        $timeLong = $times -$tokenlist['time'];

        if($tokenlist == null){
            // 先获取微信token , 用微信id 微信秘钥 缓存token
            $wxId = 'wx6d56deba07e30f78';
            $wxSecret = 'c0097e752473e624501812dbea51f69d';
            $getToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$wxId&secret=$wxSecret";
             // get请求
            $result = file_get_contents($getToken);
            // json转成数组
            $arrResult = json_decode($result, TRUE);
            // 获得token
            $token = $arrResult['access_token'];
            $arr  = array('token' =>  $token,'time' =>$times );
            $access_token -> add($arr);
          
            $data_string  = array('page' => "pages/service/service", 'scene' => "$id");
            $data_string =  json_encode($data_string);
            
            $ch = curl_init("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token");
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //curl_setopt($ch, CURLOPT_ENCODING, "");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string)
            ));

          $result =  curl_exec($ch);
            if (curl_errno($ch)) {
                print curl_error($ch);
                }
            curl_close($ch);

           echo $result;

        }elseif( $timeLong > 7200){
            // 先获取微信token , 用微信id 微信秘钥 缓存token
            $wxId = 'wx6d56deba07e30f78';
            $wxSecret = 'c0097e752473e624501812dbea51f69d';
            $getToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$wxId&secret=$wxSecret";
             // get请求
            $result = file_get_contents($getToken);
            // json转成数组
            $arrResult = json_decode($result, TRUE);
            // 获得token
            $token = $arrResult['access_token'];
            $arr  = array('token' =>  $token,'time' =>$times );
            $access_token ->where("id ={$tokenlist['id']}") -> save($arr);

            
            $data_string  = array('page' => "pages/service/service", 'scene' => "$id");
            $data_string =  json_encode($data_string);
            
            $ch = curl_init("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token");
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //curl_setopt($ch, CURLOPT_ENCODING, "");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string)
            ));

          $result =  curl_exec($ch);
            if (curl_errno($ch)) {
                print curl_error($ch);
                }
            curl_close($ch);
            
           echo $result;




        }else{
            $token =$tokenlist['token'];
            
            $data_string  = array('page' => "pages/service/service", 'scene' => "$id");
            $data_string =  json_encode($data_string);
            
            $ch = curl_init("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token");
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            //curl_setopt($ch, CURLOPT_ENCODING, "");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string)
            ));

          $result =  curl_exec($ch);
            if (curl_errno($ch)) {
                print curl_error($ch);
                }
            curl_close($ch);
            
           

           echo $result;
        }
       

    }

}